import { PlusOutlined, CopyOutlined, InboxOutlined } from '@ant-design/icons';
import {
  Divider,
  message,
  Input,
  Table,
  Tag,
  Tabs,
  Card,
  Upload,
  Collapse,
  Empty,
  Popover,
} from 'antd';
import React, { useState, useRef, useEffect, useImperativeHandle, forwardRef } from 'react';
import { useIntl, FormattedMessage, history, Link, ConnectProps, connect } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import {
  getTaskDetail,
  getPredictInfo,
  getpredicted
} from './service';
import './detail.less';

import { getStatus } from '../const';
import axios from 'axios';
import TagLine from '@/components/tagLine';

import ReactJson from 'react-json-view';
import InfoTitle from '@/components/InfoShow/InfoTitle';
import CommenDescription from '@/components/InfoShow/CommenDescription';
import CopyToClipboard from 'react-copy-to-clipboard';

import '../style.less';
import format from '@/utils/format';
import trans from '@/utils/translate';

const { TextArea } = Input;
const { Panel } = Collapse;
const jsonConfig = {
  enableClipboard: false,
  enableEdit: false,
  enableAdd: false,
  enableDelete: false,
  theme: 'ocean',
  displayObjectSize: false,
  displayDataTypes: false,
};

interface Props extends ConnectProps {}
const InferenceDetail: React.FC<Props> = (props) => {
  const [inference, setInference] = useState({});
  const [root, setRoot] = useState({});

  const [deviceType,setDeviceType] = useState('')
  const [predictHost, setPredictHost] = useState('');
  const [predictUrl, setPredictUrl] = useState('');
  const [url, setUrl] = useState('');
  const [imgUrl, setImgUrl] = useState('');
  const [guide, setGuide] = useState({
    inputParams: [],
    outputParams: [],
  });

  const [info, setInfo] = useState({ models: [{}] });
  const [basic, setBasic] = useState({});

  const params_columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'type',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
  ];
  const api_table_config = {
    bordered: true,
    // pagination: 'false',
    style: { marginBottom: '20px' },
  };
  // console.log(props);
  // const { match } = props;
  // console.log(match);
  // const { id: appid } = match?.params as { id: string};
  // console.log(appid);

  const { location } = props;
  const { appId } = location?.query as { appId: string};

  // const appid = props.location.query.appId;

  function uploadImage(base: any) {
    let data = {
      inputs: [
        {
          data: base,
        },
      ],
    };
    let token = localStorage.getItem('token');
    console.log(deviceType,url)
    if(deviceType=="NPU"){
      let url_ = "/endpoints"+url.split('/endpoints').pop()
      console.log(url_)
      axios(`${url_}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          uid: '40000',
          gid: '0',
          cid: '0',
          Accept: 'application/json',
          Authorization: 'Bearer ' + token,
        },
        data: data,
      }).then((res) => {
        setRoot(res.data)
        console.log('res',res);
      });
    }else{
      console.log("axios")
      axios(predictUrl, { // 这里改为 proxyUrl，后端传
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          uid: '40000',
          gid: '0',
          cid: '0',
          Accept: 'application/json',
          Authorization: 'Bearer ' + token,
          predictUrl:url,
          // predictUrl:predictUrl,
          predictHost:predictHost
        },
        data: data,
      }).then((res) => {
        setRoot(res.data)
        console.log('res');
      });
      // getpredicted()
    }

  }
  useEffect(() => {
    getTaskDetail(appId).then((res) => {
      if (res && res.code == 0) {
        const { data } = res;
        if (data.models.length == 0) {
          data.models.push({ name: '无', version: '无' });
        }
        setDeviceType(data.deviceType)
        setInfo(data);
        setBasic({
          serviceName: data.name,
          serviceId: data.serviceId,
          status: getStatus(data.status),
          // serviceId: data.serviceId,
          describe: data.describe,
          modelName: data.models[0].name,
          modelVersion: data.models[0].version,
          deviceType: data.deviceType,
          startTime: format(data.startTime),
        });
      }
    });
    getPredictInfo(appId).then((res) => {
      if (res && res.code == 0) {
        let data = res.data;
        console.log(data);
        setPredictHost(data.predictHost);
        setPredictUrl(data.proxyUrl);
        setUrl(data.url);
        setGuide(data.center);
      } else {
        message.error('推理初始化内容失败');
      }
    });
  }, []);

  return (
    <PageContainer
      title={trans('deployOnline.centralInference.centralInferenceDetail')}
      onBack={function () {
        window.location.href = './';
      }}
      ghost={false}
    >
      <Card bodyStyle={{ padding: ' 16px' }}>
        <InfoTitle title='document.basic'></InfoTitle>
        <CommenDescription obj={basic} prefix='deployOnline.centralInference'></CommenDescription>
        <Divider type="horizontal" dashed></Divider>

        <Tabs defaultActiveKey="1" type="card">
          <Tabs.TabPane tab={trans('deployOnline.centralInference.forecast')} key="1">
            <div style={{ display: 'flex' ,minHeight:"400px"}}>
              <div style={{ flex: 1, marginRight: '20px' ,height:"300px"}}>
                <div style={{ marginBottom: '10px', verticalAlign: 'center' }}>
                  <span
                    style={{
                      display: 'inline-block',
                      width: '2px',
                      height: '12px',
                      backgroundColor: 'blue',
                      marginRight: '10px',
                    }}
                  ></span>
                  文件上传
                </div>
                <Upload
                  style={{width:'100%',height:'100%'}}
                  accept=".jpg,.png,.bmp,.jpeg"
                  name="file"
                  showUploadList={true}
                  listType="picture-card"
                  maxCount={1}
                  multiple={false}
                  beforeUpload={() => {
                    return false;
                  }}
                  onChange={(info) => {
                    const file = info.file;
                    if(!info.fileList || info.fileList.length === 0){
                      setImgUrl('');
                      setRoot({});
                    }
                    else{
                      const reader = new FileReader();
                      reader.addEventListener(
                        'load',
                        function () {
                          let base64 = String(reader.result)?.split(',').pop();
                          setImgUrl(reader.result);
                          uploadImage(base64);
                        },
                        false,
                      );
                      reader.readAsDataURL(file);
                      const { status } = info.file;
                    }
                  }}
                  >
                    {!imgUrl &&
                    <div className="ant-upload ant-upload-drag" style={{border: 'none', height: '300px'}}>
                      <div className="ant-upload-btn">
                        <div className="ant-upload-drag-container">
                          <p className="ant-upload-drag-icon">
                          <InboxOutlined />
                          </p>
                          <p className="ant-upload-text">点击或将图片拖到这里上传</p>
                          <p className="ant-upload-hint">
                          图片类型为jpg,png,bmp,jpeg,图片大小限制在4M以内
                          </p>
                        </div>
                      </div>
                    </div>
                    }
                </Upload>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ marginBottom: '10px', verticalAlign: 'center' }}>
                  <span
                    style={{
                      display: 'inline-block',
                      width: '2px',
                      height: '12px',
                      backgroundColor: 'blue',
                      marginRight: '10px',
                    }}
                  ></span>
                  预测结果
                </div>

                <div
                  style={{
                    backgroundColor: '#2B303B',
                    borderRadius: '5px',
                    padding: '10px',
                    // height: '180px',
                  }}
                >
                  <ReactJson src={root} {...jsonConfig} />
                </div>
              </div>
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane tab="调用指南" key="2">
            <div className="api-info">
              {url.length > 0 && (
                <Collapse defaultActiveKey={['1']}>
                  <Panel header={
                    <span>
                      <Popover content={
                        <div style={{width: '300px', wordBreak: 'break-all'}}>
                          {url}
                        </div>
                      }>
                        <span className='textEllipsis' style={{width: 'auto', display: 'inline-block', marginBottom: '-6px', marginRight:'6px'}}>
                          {url}
                        </span>
                        <span onClick={(e) => e.stopPropagation()} style={{display: 'inline-block'}}>
                            <CopyToClipboard
                              text={url}
                              onCopy={(e) => {
                                message.info('复制成功');
                              }}
                            >
                              <CopyOutlined style={{ cursor: 'pointer', bottom: '15px' }} />
                            </CopyToClipboard>
                        </span>
                      </Popover>
                    </span>
                  } key='1'>
                    <TagLine title="请求类型" />
                    <Tag color="blue" style={{ marginBottom: '20px' }}>
                      POST
                    </Tag>
                    <TagLine title="请求参数" />
                    <Table
                      pagination={false}
                      dataSource={guide.inputParams}
                      columns={params_columns}
                      {...api_table_config}
                    />
                    <TagLine title="返回数据" />
                    <Table
                      pagination={false}
                      dataSource={guide.outputParams}
                      columns={params_columns}
                      {...api_table_config}
                    />
                  </Panel>
                </Collapse>
              )}
              {url.length == 0 && <Empty />}
            </div>
          </Tabs.TabPane>
          {/* <Tabs.TabPane tab="监控信息" key="3">
            <Empty />
          </Tabs.TabPane>
          <Tabs.TabPane tab="日志" key="4">
            <div style={{display:"flex",marginBottom:"20px"}}>
            <Button type="primary">获取日志</Button>
            <Button type="link" style={{marginLeft:"auto"}}>下载所有日志</Button>
            </div>
          <TextArea rows={4} value='asd' disabled/>
          </Tabs.TabPane> */}
        </Tabs>
      </Card>
    </PageContainer>
  );
}

export default connect()(InferenceDetail);
